package com.justech.mes.utils;

import com.zlyx.easycore.tool.Ops;
import com.zlyx.easycore.utils.ObjectUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.List;
import java.util.Properties;

/**
 * @author feifei.li
 */
public class AbstractMailSender2 {

    protected String hostName;

    public boolean isDebug = false;

    private String host;

    private String password;

    protected String targets;

    public AbstractMailSender2(String host, String password, String targets) {
        this.host = host;
        this.password = password;
        this.targets = targets;
    }

    /**
     * 发送邮件
     *
     * @param title
     * @param context
     * @param filepath
     * @return
     * @throws Exception
     */
    protected void sendMail(String title, String context, String name, List<String> filepath) throws Exception {
        if (ObjectUtils.isEmpty(targets)) {
            throw new Exception("请设置发送目标 => targets属性为空");
        }
        String hostname = getHostName();
        Properties props = makeMailProperties(host, hostname);
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(host, password);
            }
        });
        session.setDebug(isDebug);
        Transport ts = session.getTransport();
        ts.connect(hostname, host, password);
        Message message = targets.contains(",") ?
                createEmailByGroupAndFile(name, session, title, context, filepath == null ? null : filepath) :
                createEmail(name, session, title, context);
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }

    /**
     * 创建邮件信息
     *
     * @param host
     * @param hostname
     * @return
     */
    private Properties makeMailProperties(String host, String hostname) {
        Properties props = new Properties();
        props.put("mail.smtp.host", hostname);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        String suffix = ".qq.com";
        if (hostname.indexOf(suffix) != -1) {
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }
        return props;
    }

    /**
     * 创建邮件消息
     *
     * @param session
     * @param
     * @param
     * @param title
     * @param context
     * @return
     * @throws MessagingException
     * @throws AddressException
     */
    private Message createEmail(String name, Session session, String title, String context) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(host, name, "UTF-8"));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(targets));
        message.setSubject(title);
        message.setContent(context, "text/html;charset=UTF-8");
        message.saveChanges();
        return message;
    }

    /**
     * 创建群发带附件
     *
     * @param session
     * @param title
     * @param context
     * @param filepath
     * @return
     */
    private Message createEmailByGroupAndFile(String name, Session session, String title, String context, List<String> filepath) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(host, name, "UTF-8"));
        // 创建收件人列表
        if (targets != null && targets.trim().length() > 0) {
            String[] arr = targets.split(",");
            int receiverCount = arr.length;
            if (receiverCount > 0) {
                InternetAddress[] address = new InternetAddress[receiverCount];
                for (int i = 0; i < receiverCount; i++) {
                    address[i] = new InternetAddress(arr[i]);
                }
                message.setRecipients(Message.RecipientType.TO, address);
            }
        }
        Multipart mp = new MimeMultipart();
        if (filepath != null && filepath.size() > 0) {
            for (String filename : filepath) {
                MimeBodyPart mbp = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(filename);
                mbp.setDataHandler(new DataHandler(fds));
                mbp.setFileName(fds.getName());
                mp.addBodyPart(mbp);
            }
            MimeBodyPart mbp = new MimeBodyPart();
            mbp.setText(context);
            mp.addBodyPart(mbp);
            filepath.clear();
            message.setContent(mp);
        } else {
            message.setContent(context, "text/html;charset=UTF-8");
        }
        message.setSubject(title);
        message.saveChanges();
        return message;
    }

    /**
     * 返回主机
     *
     * @return
     */
    private String getHostName() {
        return Ops.isEmpty(this.hostName) ? "smtp." + host.split("@")[1] : this.hostName;
    }
}
